@echo off
chcp 65001 >nul
title Sihe Think Tank - Startup
color 0B

echo.
echo ============================================================
echo  Sihe Think Tank v2.1.2
echo ============================================================
echo.

:: Check dependencies
echo [CHECK] Checking environment...
echo.

:: Check Python
python --version >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Python not found! Please install Python 3.11+
    pause
    exit /b 1
)
echo [OK] Python installed

:: Check Node.js
node --version >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Node.js not found! Please install Node.js 18+
    pause
    exit /b 1
)
echo [OK] Node.js installed

:: Check PostgreSQL
netstat -ano | findstr :5432 >nul 2>&1
if errorlevel 1 (
    echo [WARN] PostgreSQL may not be running!
    echo Please ensure PostgreSQL is running on port 5432
    pause
)
echo [OK] PostgreSQL is running

:: Check Ollama
curl -s http://localhost:11434/api/tags >nul 2>&1
if errorlevel 1 (
    echo [WARN] Ollama may not be running!
    echo Please ensure Ollama is running on port 11434
    pause
)
echo [OK] Ollama is running

echo.
echo ============================================================
echo  Starting services...
echo ============================================================
echo.

:: Force cleanup ports 3301 and 3300 before start
echo [CLEAN] Force checking and cleaning ports 3301 and 3300...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ports = @(3301, 3300); foreach ($port in $ports) { Write-Host ('[CHECK] Checking port ' + $port + '...') -ForegroundColor Yellow; $maxRetries = 3; $retry = 0; do { $connections = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue; if ($connections) { $processIds = $connections | Select-Object -ExpandProperty OwningProcess -Unique | Where-Object { $_ -gt 0 }; if ($processIds.Count -eq 0) { Write-Host ('[INFO] Port ' + $port + ' has system connections (PID 0), ignoring...') -ForegroundColor Cyan; Write-Host ('[OK] Port ' + $port + ' is available for use') -ForegroundColor Green; break } else { Write-Host ('[WARN] Port ' + $port + ' is occupied by PIDs: ' + ($processIds -join ', ')) -ForegroundColor Red; foreach ($processId in $processIds) { try { $proc = Get-Process -Id $processId -ErrorAction SilentlyContinue; if ($proc) { $name = $proc.ProcessName; Stop-Process -Id $processId -Force -ErrorAction Stop; Write-Host ('[OK] Killed ' + $name + ' (PID: ' + $processId + ') on port ' + $port) -ForegroundColor Green } } catch { Write-Host ('[WARN] Failed to kill PID: ' + $processId) -ForegroundColor Yellow } }; Start-Sleep -Seconds 3; $retry++ } } else { Write-Host ('[OK] Port ' + $port + ' is free') -ForegroundColor Green; break } } while ($retry -lt $maxRetries); if ($retry -ge $maxRetries -and $connections) { $remaining = $connections | Select-Object -ExpandProperty OwningProcess -Unique | Where-Object { $_ -gt 0 }; if ($remaining.Count -gt 0) { Write-Host ('[ERROR] Port ' + $port + ' still occupied after ' + $maxRetries + ' attempts!') -ForegroundColor Red } } }"
echo [CLEAN] Port cleanup completed. Waiting 2 seconds for ports to fully release...
timeout /t 2 /nobreak >nul
echo.

:: Start backend (new window with PowerShell script)
echo [1/2] Starting backend service (port 3301)...
start "Sihe-Backend" powershell -NoExit -ExecutionPolicy Bypass -File "%~dp0start_backend.ps1"
timeout /t 3 /nobreak >nul

:: Start frontend (new window with PowerShell script)
echo [2/2] Starting frontend service (port 3300)...
start "Sihe-Frontend" powershell -NoExit -ExecutionPolicy Bypass -File "%~dp0start_frontend.ps1"
timeout /t 3 /nobreak >nul

echo.
echo ============================================================
echo  Services started successfully!
echo ============================================================
echo.
echo  Frontend: http://localhost:3300
echo  Backend:  http://localhost:3301
echo  API Docs: http://localhost:3301/docs
echo.
echo  Test Account:
echo    Username: admin
echo    Password: admin123
echo.
echo  Tips:
echo  - Two new windows opened (frontend and backend)
echo  - Close window or press Ctrl+C to stop service
echo  - This window can be closed safely
echo.
echo ============================================================
echo.
echo Press any key to wait 8 seconds and open browser...
pause >nul

:: Wait for services to fully start
echo.
echo Waiting for services to start...
timeout /t 8 /nobreak >nul

:: Open browser
start http://localhost:3300

echo.
echo Browser opened!
echo.
pause
